﻿/// <reference path="jquery-1.7.2.js" />
/// <reference path="central.core.js" />
/// <reference path="underscore.js" />

; (function ($) {
    if (!$.PrepareQuery) {
        $.PrepareQuery = {};
    }

    $.PrepareQuery.queryBuilder = function (el, queryParams, options) {

        var types = central.utils.types;

        var self = this; self.$el = $(el); self.el = el;

        self.$el.data("PrepareQuery.queryBuilder", self);

        self.init = function () {
            self.currentQueryParams = queryParams;
            self.settings = $.extend(true, {}, $.PrepareQuery.queryBuilder.settings, options);
            self.loadFields();
        }

        self.loadFields = function () {
            if (!self.settings.fieldsUrl) {
                alert('Не задан url для получения списка полей ' + self.currentQueryParams.EntityName);
            }
            else {
                $.ajax({
                    url: self.settings.fieldsUrl,
                    data: {},
                    type: 'GET',
                    dataType: 'json',
                    contentType: 'application/json; charset=utf-8',
                    success: function (result) {
                        self.$el.data('fields', result);
                        self.drawCurrentQueryParams();
                    },
                    error: function (jqXHR, textStatus) {
                        alert(textStatus);
                    }
                });
            }
        }

        self.drawCurrentQueryParams = function () {
            var level = 0;
            if (self.settings.showFilters) {
                var $filterContainer = $(document.createElement('div'));
                $filterContainer.attr('id', self.settings.containerFiltersName + 0);
                $filterContainer.attr('class', 'qbFilters');
                if (self.currentQueryParams) {
                    self.$el.append($filterContainer);
                    self.drawFilters(self.currentQueryParams.Filters, $filterContainer, level);
                }

                //if (self.currentQueryParams.Filters.LogicalOperator === 'Or')
                //    $('[id^="' + self.settings.logicalPrefix, $filterContainer).text('ИЛИ');
                //else
                //    $('^' + self.settings.logicalPrefix).text('И');
                $('span[data-operator="Or"').text('ИЛИ');
                $('span[data-operator="And"').text('И');


                self.$el.append($filterContainer);
            }
            if (self.settings.showSorters) {
                var $sorterContainer = $(document.createElement('div'));
                $sorterContainer.attr('id', self.settings.containerSortersName);
                self.$el.append($sorterContainer);
            }
            if (self.settings.showGroupers) {
                var $grouperContainer = $(document.createElement('div'));
                $grouperContainer.attr('id', self.settings.containrerGroupersName);
                self.$el.append($grouperContainer);
            }
        };

        self.drawFilters = function (items, $container, drawLevel) {
            $container.append('<div id="filters'
                + drawLevel
                + '"><h3>Фильтры объеденины по типу <span id="'
                + self.settings.logicalPrefix + drawLevel
                + '" data-operator="' + items.LogicalOperator + '">'
                + items.LogicalOperator
                + '</span></h3></div>');
            for (var i = 0; i < items.FilterParams.length; i++) {
                var $filterName = $(document.createElement('div'));
                var $closeButton = $(document.createElement('div'));
                $closeButton.attr('id', 'close');
                $filterName.attr('class', 'qbFilterItem');
                var txt = '"' + items.FilterParams[i].DisplayName + '" ' +
                    self.checkDisplayName(items.FilterParams[i].Operator) + ' ' +
                    items.FilterParams[i].Value;
                $filterName.text(txt);
                $filterName.append($closeButton);
                $container.append($filterName);
            }
            if (items.JsonFilterManagers.length > 0) {
                for (var i = 0; i < items.JsonFilterManagers.length; i++) {

                    var $filterContainerInner = $(document.createElement('div'));
                    $filterContainerInner.attr('id', self.settings.containerFiltersName + (drawLevel + 1));
                    $filterContainerInner.attr('class', 'qbFilters');
                    self.drawFilters(items.JsonFilterManagers[i], $filterContainerInner, drawLevel + 1);
                    $container.append($filterContainerInner);
                }
            }
        }

        self.changeOperator = function (type) {
            return _.filter(types, function (model) { return model.type === 1 });
        };

        self.checkDisplayName = function (name) {
            return _.find(types, function (model) { return model.name == name; }).displayName;
        };

        self.init();
    }


    $.PrepareQuery.queryBuilder.settings = {
        fieldsUrl: '/home/personfields/',
        containerFiltersName: 'prepareFilters',
        containerSortersName: 'prepareDorters',
        containrerGroupersName: 'prepareGroupers',
        showFilters: true,
        showSorters: true,
        showGroupers: true,
        logicalPrefix: 'logicalOperator'
    }

    $.fn.queryBuilder = function (queryParams, options) {
        return this.each(function () {
            (new $.PrepareQuery.queryBuilder(this, queryParams, options));
        });
    };

}(jQuery));